package com.mzd.multipledatasources2.controller;

import com.mzd.multipledatasources2.bean.TeachersBean;
import com.mzd.multipledatasources2.bean.UserBean;
import com.mzd.multipledatasources2.service.TransactionService1;
import com.mzd.multipledatasources2.service.TransactionService2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * 多数据源事务测试
 *
 * @author acer
 */
@RestController
public class TransactionController {

    @Autowired
    private TransactionService1 ts1;
    @Autowired
    private TransactionService2 ts2;

    @RequestMapping("/savetest.do")
    public Object saveTest() {
        UserBean tb = new UserBean();
        tb.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        tb.setScore(70);
        tb.setClassId("1");
        tb.setUserId("a");
        return ts1.savetestBean(tb);
    }

    @RequestMapping("/saveteacher.do")
    public Object saveTeacher() {
        TeachersBean tb = new TeachersBean();
        tb.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        tb.setTeacherName("王老师");
        tb.setClassId("1");
        return ts2.saveTeacher(tb);
    }

    // ########################开始事务测试##########################

    /**
     * 结果是一个插入进去了，属于非正常现象
     */
    @RequestMapping("/test.do")
    public String test() {
        UserBean tb = new UserBean();
        tb.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        tb.setScore(70);
        tb.setClassId("1");
        tb.setUserId("a");
        ts1.savetestBean2(tb);
        return "success";
    }

    /**
     * 结果是两个都没法插入---属于正常现象
     */
    @RequestMapping("/test2.do")
    public String test2() {
        UserBean tb = new UserBean(
                UUID.randomUUID().toString().replaceAll("-", "")
                , "a"
                , 70
                , "1");
        ts1.savetestBean3(tb);
        return "success";
    }

    /**
     * 结果是一个插入进去了，属于非正常现象
     */
    @RequestMapping("/test3.do")
    public String test3() {
        UserBean tb = new UserBean();
        tb.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        tb.setScore(70);
        tb.setClassId("1");
        tb.setUserId("a");
        ts1.savetestBean4(tb);
        return "success";
    }
}
